<script setup lang="ts">
import {
	Table,
	Row,
	Checkbox,
	Col,
	Modal,
	Tooltip,
	message,
} from "ant-design-vue";
import { reactive, h, ref, watch } from "vue";
import { ColumnType } from "ant-design-vue/lib/table";
import { isEmpty, isNil } from "lodash-es";
import type { FilterChild } from "./index";

const props = defineProps(["clumnsDataList"]);
const emits = defineEmits(["ok"]);
const okLoading = ref(false);

interface IExportModalState {
	display: boolean;
	batchingExports: {
		select: string[];
		records: Dict[];
	};
	tableChecke: {
		checkAll: boolean;
		indeterminate: boolean;
	};
}

const exportsModalState = reactive<IExportModalState>({
	display: false,
	batchingExports: {
		select: [],
		records: [],
	},
	tableChecke: {
		checkAll: true,
		indeterminate: false,
	},
});

let activeFilter = ref<FilterChild[]>([]);

const tables = reactive<{
	loading: boolean;
	dataSource: MergeType<{ id: string; field: string }>[];
}>({
	loading: false,
	dataSource: [],
});

const closeExportModal = () => {
	exportsModalState.display = false;
};

const onOk = async () => {
	let reIds = exportsModalState.batchingExports.select;

	if (exportsModalState.batchingExports.select.length === 0) {
		message.error("请选择待导出项");
		return;
	}

	okLoading.value = true;

	emits("ok", {
		complete: (r?: boolean) => {
			okLoading.value = false;
			if (r) {
				closeExportModal();
			}
		},
		fields: tables.dataSource
			.filter((el) => reIds.includes(el.id))
			.map((el) => el.field),
		filters: activeFilter.value,
	});
};

const displayExportModel = async (argv?: FilterChild[]) => {
	activeFilter.value = argv.filter((el) => !isEmpty(el.value));
	okLoading.value = false;
	// 参数中会获取到要请求的参数
	exportsModalState.display = true;
	let ids = [];
	tables.dataSource = props.clumnsDataList.map((el, i) => {
		ids.push(el.dataIndex);
		return {
			fieldDescribe: el.title,
			field: el.dataIndex,
			index: i + 1,
			id: el.dataIndex,
		};
	});

	exportsModalState.batchingExports.select = ids;
};

// 监听table select的选中状态，是否选择或全选
watch(
	() => exportsModalState.batchingExports.select,
	(newVal) => {
		const len = newVal.length;
		exportsModalState.tableChecke.indeterminate =
			len > 0 && len < tables.dataSource.length;
		exportsModalState.tableChecke.checkAll = len === tables.dataSource.length;

		exportsModalState.batchingExports.records = tables.dataSource.filter((el) =>
			newVal.includes(el.id)
		);
	}
);

const exportModalTableColumns: ColumnType[] = [
	{ title: "序号", dataIndex: "index", width: 80 },
	{ title: "排序", dataIndex: "sort", width: 100 },
	{ title: "字段描述", dataIndex: "fieldDescribe" },
];

const exportModelTblSelectChange = (used: string[], records) => {
	exportsModalState.batchingExports.select = used;
	exportsModalState.batchingExports.records =
		records.length === 0 ? null : records;
};

// 点击多选框，是否全部选中
const onTableSelectChangeAll = (e) => {
	let checked = e.target.checked;
	exportsModalState.batchingExports.select = checked
		? (tables.dataSource.map((el) => el.id) as string[])
		: [];

	if (exportsModalState.tableChecke.indeterminate) {
		exportsModalState.tableChecke.indeterminate = false;
	}
};

const swap = (ai: number, bi: number) => {
	if (bi < 0 || tables.dataSource.length <= bi) {
		return;
	}
	let src = tables.dataSource;
	[src[ai], src[bi]] = [src[bi], src[ai]];
	tables.dataSource = [...src];
};

const sortUp = (i: number) => {
	swap(i, i - 1);
};

const sortDown = (i: number) => {
	swap(i, i + 1);
};

defineExpose({
	display: displayExportModel.bind(null),
});
</script>

<template>
	<Modal
		:confirmLoading="okLoading"
		:maskClosable="!okLoading"
		title="导出设置"
		v-model:visible="exportsModalState.display"
		width="720px"
		@ok="onOk"
	>
		<header class="export-modal-header flex">
			<div class="desc-header flex items-center">已筛选条件</div>
			<Row
				:gutter="[4, 8]"
				class="py:14 px:10 modal-header"
				justify="space-between"
			>
				<Col
					v-for="el in activeFilter"
					:key="el.key"
					:span="10"
					class="flex flex-nowrap overflow-hidden"
				>
					<span class="d-inline-block text-nowrap text-label color-black-65">
						{{ el.label }}
					</span>
					<a-tooltip>
						<template #title>
							<span>{{ isNil(el.value) ? "--" : el.value }}</span>
						</template>
						<span class="d-inline-block modal-value single-cut color-black-85">
							{{ isNil(el.value) ? "--" : el.value }}
						</span>
					</a-tooltip>
				</Col>
			</Row>
		</header>
		<Table
			:loading="tables.loading"
			:columns="exportModalTableColumns"
			rowKey="id"
			:rowSelection="{
				columnWidth: 60,
				selectedRowKeys: exportsModalState.batchingExports.select,
				onChange: exportModelTblSelectChange,
				columnTitle: h(
					'div',
					h(Checkbox, {
						checked: exportsModalState.tableChecke.checkAll,
						indeterminate: exportsModalState.tableChecke.indeterminate,
						onChange: onTableSelectChangeAll,
					})
				),
			}"
			:dataSource="tables.dataSource"
			:pagination="false"
		>
			<template v-slot:bodyCell="{ column, index }">
				<template v-if="column.dataIndex === 'index'">{{ index + 1 }}</template>
				<template v-if="column.dataIndex === 'sort'">
					<div>
						<Tooltip title="向上排序">
							<div
								class="sort-border d-inline-block cursor-pointer text-color"
								v-if="index > 0"
								@click="sortUp(index)"
							>
								<i class="icon iconfont icon-arrow_up"></i>
							</div>
							<div class="sort-border d-inline-block cursor-disabled" v-else>
								<i class="icon iconfont icon-arrow_up"></i>
							</div>
						</Tooltip>
						<Tooltip title="向下排序">
							<div
								class="sort-border d-inline-block cursor-pointer text-color"
								v-if="index < tables.dataSource.length - 1"
								@click="sortDown(index)"
							>
								<i class="icon iconfont icon-zhaoxia"></i>
							</div>
							<div class="sort-border d-inline-block cursor-disabled" v-else>
								<i class="icon iconfont icon-zhaoxia"></i>
							</div>
						</Tooltip>
					</div>
				</template>
			</template>
		</Table>
	</Modal>
</template>

<style lang="less">
.export-modal-header {
	border: 1px solid #eeeeee;

	.desc-header {
		width: 107px;
		background-color: #0050b31a;
		font-size: 16px;
		color: #000000;
		min-height: 47px;
		padding: 0 12px;
	}
}

.modal-header {
	width: calc(100% - 104px);

	column-gap: 8px;

	.modal-value {
		vertical-align: bottom;
		flex-grow: 1;
	}
}

.modal-key {
	width: 200px;
}

.sort-border {
	text-align: center;
	line-height: 26px;
	width: 26px;
	height: 26px;
	border: 1px solid @border-color-base;

	i {
		font-size: 18px;
	}
}

.sort-border + .sort-border {
	margin-left: 4px;
}
</style>
